/*
    此文件对原始数据进行去标签操作
        将 input中的数据去标签 放置在 raw_html目录下
    文档与文档之间用\3（不可显字符）间隔，文档中不存在换行等控制字符

*/
#include<iostream>
#include<string>
#include<vector>
//#include<fstream>
#include<boost/filesystem.hpp>
#include"util.hpp"

//原始数据存放目录
const std::string src_path = "data/input";
//处理后的数据存放目录
const std::string output = "data/raw_html/raw.txt";

typedef struct DucInfo{
    std::string title;//标题
    std::string content;//内容
    std::string url;//对应的url
}DucInfo_t;

// 递归式的将每个html文件名带路径，保存到File_list中，方便后期对文件读取
bool EnumFile(const std::string &src_path, std::vector<std::string> *file_list)
{
    namespace fs = boost::filesystem;
    fs::path root_path (src_path);
    //若路径不存在
    if(!fs::exists(src_path)){
        std::cerr<<src_path<<"not exists"<<std::endl;
        return false;
    }
    //空迭代器 判断递归是否结束
    fs::recursive_directory_iterator end;
    for(fs::recursive_directory_iterator iter(root_path);iter != end;iter++){
        //判断是否为普通文件
        if(!fs::is_regular_file(*iter))
            continue;
        //判断是否为.html文件   extension获取文件后缀
        if(iter->path().extension() != ".html")
            continue;
        //std::cout<<"file:   "<<iter->path().string()<<std::endl;
        file_list->push_back(iter->path().string());
    }
    return true;
}

static bool ParseTitle(std::string file, std::string *title){
    std::size_t begin = file.find("<title>");
    if(begin == std::string::npos){
        return false;
    }
    std::size_t end = file.find("</title>");
    if (end == std::string::npos)
    {
        return false;
    }
    begin += std::string("<title>").size();
    if(begin >= end){
        return false;
    }
    *title = file.substr(begin , end-begin);
    return true;
}

static bool ParseContent(const std::string file,std::string *content){
    //去标签,基于一个简单的状态机
    enum status{
        LABLE,
        CONTENT
    };
    enum status s = LABLE;
    for(char c : file){
        switch(s){
            case LABLE:
                if(c == '>') s = CONTENT;
                break;
            case CONTENT:
                if (c == '<')
                    s = LABLE;
                else{
                    if(c == '\n')c=' ';
                    content->push_back(c);
                }
                break;
            default:
                break;
        }
    }
    return true;
}

static bool ParseUrl(const std::string &file_path,std::string *url){
    std::string url_head = "https://www.boost.org/doc/libs/1_85_0/doc/html";
    std::string url_tail = file_path.substr(src_path.size());
    *url = url_head + url_tail;
    return true;
}
static void Show(const DucInfo_t t){
    std::cout<<"title :"<<t.title<<std::endl;
    std::cout << "content :" << t.content << std::endl;
    std::cout << "url :" << t.url << std::endl;
    std::cout<<std::endl;
}
// 读取并解析文件
bool PerseHtml(const std::vector<std::string> &file_list, std::vector<DucInfo_t> *results)
{
    for(const std::string &file : file_list){
        // read
        std::string result;
        if (!util::FileUtil().ReadFile(file,&result)){
            continue;
        }
        DucInfo_t doc;
        // 提取title
        if (!ParseTitle(result, &doc.title))
        {
            continue;
        }
        // 提取content
        if (!ParseContent(result, &doc.content))
        {
            continue;
        }
        // 提取url
        if (!ParseUrl(file,&doc.url))
        {
            continue;
        }
        results->push_back(std::move(doc));

        //debug
        //Show(doc);
        break;
    }
    return true;
}
#define SEP '\3'
//保存处理结果
bool SaveFile(const std::vector<DucInfo_t> &result, const std::string &output)
{
    std::ofstream save(output,std::ios::out | std::ios::binary);
    if(!save.is_open()){
        std::cerr << "open :"<<output<<" falled"<<std::endl;
        return false;
    }
    for(auto&tmp : result){
        std::string out_stream;
        out_stream += tmp.title;
        out_stream += SEP;
        out_stream += tmp.content;
        out_stream += SEP;
        out_stream += tmp.url;
        out_stream += '\n';
        save.write(out_stream.c_str(),out_stream.size());
    }
    save.close();
    return true;
}
int main()
{
    std::vector<std::string> file_list;
    if(!EnumFile(src_path,&file_list)){
        std::cout<< "enum file name error"<<std::endl;
        return 1;
    }

    std::vector<DucInfo_t> result;
    if (!PerseHtml(file_list,&result))
    {
        std::cout << "perse file error" << std::endl;
        return 2;
    }

    if (!SaveFile(result,output))
    {
        std::cout << "save file error" << std::endl;
        return 3;
    }
}